import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import NProgress from '@/utils/progress'
import sysCache from '@/utils/cache'
import projectSetting from '@/settings/projectSetting'
import store from '@/store/index'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login/login.vue')
  },
  {
    path: '/',
    name: 'Layout',
    redirect: '/dashboard/analysis',
    component: () => import(/* webpackChunkName: "layout" */ '@/layout/index.vue'),
    children: []
  },
  {
    path: '/redirect/:path(.*)',
    name: 'Redirect',
    component: () => import(/* webpackChunkName: "redirect" */ '@/views/redirect/index.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'ErrorPage',
    component: () => import(/* webpackChunkName: "errorPage" */ '@/views/errorPage/errorPage.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

//设置标题
document.title = projectSetting.APP_NAME as string

// 导航守卫
router.beforeEach(async (to) => {
  NProgress.start()

  // 动态设置标题
  document.title = to.meta.title
    ? `${to.meta.title} - ${projectSetting.APP_NAME}`
    : `${projectSetting.APP_NAME}`

  if (to.path !== '/login') {
    const token = sysCache.localCache.getCache('token')
    if (!token) {
      return '/login'
    }

    // 动态添加路由
    if (!store.state.login.isDynamicAddedRoute) {
      const routes = await store.dispatch('buildRoutesAction', null, { root: true })
      routes.forEach((route) => {
        router.addRoute('Layout', route)
      })
      store.commit('login/setDynamicAddedRoute', true)
      router.push(to.fullPath)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
